﻿using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.CalculateUnitAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class CreateCalculateUnitCommand : CalculateUnitEditRequestDto,
        IRequest<Result<CalculateUnitInfoResponseDto>>
    {
    }

    public class
        CreateCalculateUnitCommandHandler : IRequestHandler<CreateCalculateUnitCommand,
            Result<CalculateUnitInfoResponseDto>>
    {
        private readonly ICalculateUnitRepository _calculateUnitRepository;
        private readonly IMapper _mapper;

        public CreateCalculateUnitCommandHandler(ICalculateUnitRepository calculateUnitRepository,
            IMapper mapper)
        {
            _calculateUnitRepository = calculateUnitRepository;
            _mapper = mapper;
        }

        public async Task<Result<CalculateUnitInfoResponseDto>> Handle(CreateCalculateUnitCommand request,
            CancellationToken cancellationToken)
        {
            var calculateUnit = new CalculateUnit(request.Code, request.Name, request.Description);
            _calculateUnitRepository.Add(calculateUnit);
            await _calculateUnitRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<CalculateUnitInfoResponseDto>.SuccessAsync(
                _mapper.Map<CalculateUnitInfoResponseDto>(calculateUnit));
        }
    }
}